import {ref} from 'vue'
import {defineStore} from 'pinia'
import routes from '@/router/routes'
import localStore from '@/utils/storage'
import setting from '@/config/setting'
import axios from '@/config/axios-config'
import {formatMenus, getOpenKeysMap} from '@/utils/util-menu'
import {useUserStore} from '@/stores/user'

const userStore = useUserStore()

const storeHistory = localStore.get('history')
const tabActiveStore = 'active' in storeHistory ? storeHistory.active : null
const historyStore = 'list' in storeHistory ? storeHistory.list : []

export const useRouterStore = defineStore('router', () => {
  const menus = ref(false) // 当前菜单
  const openKeyMap = ref({})  // 当前展开的菜单map
  const history = ref(historyStore) // 历史打开的菜单
  const active = ref(tabActiveStore) // 当前打开的菜单

  /**
   * 历史路由改变后进行缓存
   * @param list
   * @param route
   */
  const historyChangeTab = (list = [], route) => {
    history.value = list
    active.value = route.name
    localStore.set('history', {list: history.value, active: route.name})
  }

  /**
   * 设置当前打开的菜单
   * @param name
   */
  const historySetActive = (name) => {
    active.value = name
    localStore.set('history', {list: history.value, active: name})
  }

  /**
   * 获取动态路由菜单
   * @returns boolean|array
   */
  const addRouterMenu = async () => {
    let defaultVal = {menus: false, home: false}
    if (menus.value.menus) return defaultVal

    if (setting.menuUrl && userStore.token) {
      menus.value = defaultVal
      let result = await axios.get(setting.menuUrl)
      if (result.code === 200) {
        menus.value = formatMenus([...result.result, ...routes])
        openKeyMap.value = getOpenKeysMap(menus.value.menus)
      }
      return menus.value
    } else if (routes.length) {
      menus.value = formatMenus(routes)
      openKeyMap.value = getOpenKeysMap(menus.value.menus)
      return menus.value
    }
    return defaultVal
  }
  return {
    menus,
    history,
    active,
    openKeyMap,
    addRouterMenu,
    historyChangeTab,
    historySetActive
  }
})
